import json
from fastapi import APIRouter, Query
from fastapi.responses import JSONResponse
from typing import List, Optional
from langchain_community.llms import Ollama

router = APIRouter()

ollama = Ollama(base_url='http://172.16.21.38:11436', model="qwen3:0.6b")

@router.get("/chat")
async def chat_get(
    inputText: str = Query(..., description="用户输入消息"),
    history: Optional[str] = Query(None, description="可选历史消息 JSON 字符串")
):
    try:
        messages = json.loads(history) if history else []
        messages.append({"role": "user", "content": inputText})
    except Exception as e:
        return JSONResponse(content={"success": False, "error": f"解析 history 失败: {str(e)}"})

    try:
        # 改用 invoke() 方法
        response = ollama.invoke(messages)
        return JSONResponse(content={"success": True, "response": response})
    except Exception as e:
        return JSONResponse(content={"success": False, "error": str(e)})


@router.get("/test")
async def test():
    return JSONResponse(content={"message": "Hello World"})
